var form;
var $;
var table;
var layer;
var upload;
var node;
var user = JSON.parse(localStorage.getItem("user"));
var userId = user.userId;
layui.use(['form','jquery','table','layer','upload'],function() {
    form = layui.form;
    $ = layui.jquery;
    table = layui.table;
    layer = layui.layer;
    upload = layui.upload;

    //展示微圈列表
    getMicrocircleList('','','','');
    //展示分类树
    getJsActicleCategroy();

    table.on('row(test)', function(obj){
        console.log(obj.data);
        localStorage.setItem("microCircleData",JSON.stringify(obj.data));
    });

});

function getJsActicleCategroy() {
    $.ajax({
        url:'/microcircle/getJsActicleCategroy',
        type: "post",
        dataType:'json',
        data: {},
        success:function (data) {
            showZtree(data.data);
        }
    });
}

function showZtree(data) {
    var setting = {
        data:{
            simpleData: {
                enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                idKey: "acticleCategroyId",  //节点数据中保存唯一标识的属性名称
                pIdKey: "parentId",    //节点数据中保存其父节点唯一标识的属性名称
                rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
            },
            key: {
                name: "artcleCategroyName"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
            }
        },
        view:{
            showLine: true,
            showIcon:false,
        },
        callback:{
            onClick: showTable, //点击事件回调
            onRightClick: onRightClick //鼠标右键回调
        }
    };

    //点击对应树节点展示微圈列表
    function showTable(event,treeId,treeNode){
        /*if (!treeNode.isParent) {//treeNode为获取对应节点的json数据
            getMicrocircleList('','','',treeNode.acticleCategroyId);
        }*/
        getMicrocircleList('','','',treeNode.acticleCategroyId);
    }

    //右键展示菜单
    function onRightClick(event,treeId,treeNode) {
        node = treeNode;
        if (event.target.tagName.toLowerCase() == "span") {
            var top = event.clientY;
            var left = event.clientX;
            top -= 190;
            left -= 5;
            $("#rMenu").css('position','absolute');
            $("#rMenu").css('top',top);
            $("#rMenu").css('left',left);
            $("#rMenu").css("display","inline");
            $("body").bind("mousedown", onBodyMouseDown);
        }
    }

    //隐藏右键菜单
    function onBodyMouseDown(event) {
        if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
            $("#rMenu").css("display","none");
        }
    }

    //初始化ztree
    zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, data );
    zTreeObj.expandAll(true);//展开全部节点
}

//添加ztree树节点
function addHoverDom() {
    $("#rMenu").css("display","none");
    console.log(node.acticleCategroyId);
    //获取创建人员信息
    layer.prompt({
        formType: 2,
        value: "请输入添加分类",
        title: "添加分类",
        area: ['500px', '30px'],
    },function (value,index,elem) {
        $.ajax({
            url: "/microcircle/addZtree",
            type: "post",
            dataType: "json",
            data: {"artcleCategroyName":value,"createId":userId,"parentId":node.acticleCategroyId},
            success: function (data) {
                if (data.data) {
                    getJsActicleCategroy();
                    layer.msg("添加成功");
                }else{
                    layer.msg("添加失败");
                }
            }
        });
        layer.close(index);
    });
}

//删除ztree树节点
function delnode() {
    if (confirm("确认删除" + node.artcleCategroyName + "微圈类")){
        if (node.isParent){
            layer.msg("请从子目录开始删除");
            return false;
        }
        $.ajax({
            url: "/microcircle/delZtree",
            type: "post",
            dataType: "json",
            data: {"acticleCategroyId":node.acticleCategroyId},
            success: function (data) {
                if (data.data) {
                    getJsActicleCategroy();
                    layer.msg("删除成功");
                    $("#rMenu").css("display","none");
                    return true;
                }else{
                    layer.msg("删除失败");
                    return false;
                }
            }
        });
    }
}

//修改树节点
function Rename() {
    $("#rMenu").css("display","none");
    layer.prompt({
        formType: 2,
        value: "请输入修改分类",
        title: "修改分类",
        area: ['500px', '30px'],
    },function (value,index,elem) {
        $.ajax({
            url: "/microcircle/editZtree",
            type: "post",
            dataType: "json",
            data: {"artcleCategroyName":value,"acticleCategroyId":node.acticleCategroyId},
            success: function (data) {
                if (data.data) {
                    getJsActicleCategroy();
                    layer.msg("修改成功");
                }else{
                    layer.msg("修改失败");
                }
            }
        });
        layer.close(index);
    });
}

function getMicrocircleList(artcleTitle,account,trueName,acticleCategroyId) {
    $.ajax({
        url:'/microcircle/getMicrocircleList',
        type: "post",
        dataType:'json',
        data: {"artcleTitle": artcleTitle, "account": account,"trueName": trueName,"acticleCategroyId":acticleCategroyId},
        success:function (data) {
            //console.log(data.data);
            showMicrocircleList(data.data);
        }
    });
}

function showMicrocircleList(data) {
    console.log(data);
    table.render({
        elem: '#demo' ,
        data:data,
        page:true,
        limit: 4,
        cols:[[
            {checkbox:true},
            {field:'microcircleId',title:'序号',align:'center',height:'20px',unresize:true},
            {field:'trueName',title:'用户昵称',align:'center',unresize:true},
            {field:'artcleTitle',title:'文章标题',align:'center',unresize:true},
            {field:'createDate',title:'创建时间',width:170,align:'center',unresize:true},
            {field:'account',title:'用户账号',align:'center',unresize:true},
            {field:'acticleLike',title:'点赞数量',align:'center',unresize:true},
            {field:'collectionNum',title:'收藏数量',align:'center',unresize:true,templet:function (data) {
                    var collectionNum = 0
                    $.ajax({
                        url:'/microcircle/getCollectionNum',
                        type: "post",
                        dataType:'json',
                        async: false,
                        data: {"microcircleId": data.microcircleId },
                        success:function (data) {
                            if (data.data != null){
                                collectionNum = data.data;
                            } else{
                                collectionNum = 0;
                            }
                        }
                    });
                    return collectionNum;
                }},
            {field:'acticleReviews',title:'评论数量',align:'center',unresize:true},
            {field:'acticleShare',title:'分享数量',align:'center',unresize:true},
            {field:'',title:'操作',align:'center',width:100,unresize:true,templet:function(data){
                    return "<a class='operation' onclick='seeMicroCircle("+data.microcircleId+")'>查看</a>&nbsp&nbsp"+
                        "<a onclick='delMicroCircle(\""+data.microcircleId+"\")' class='operation'>删除</a>";
                }},
        ]],
    });
}

//搜索
$("#selMicroCircle").on("click",function () {
    var artcleTitle = $("input[name=artcleTitle]").val();
    var account = $("input[name=account]").val();
    var trueName = $("input[name=trueName]").val();
    getMicrocircleList(artcleTitle,account,trueName,'');
});

//重置
$("#reset").on("click",function () {
    $("input[name=artcleTitle]").val('');
    $("input[name=account]").val('');
    $("input[name=trueName]").val('');
    getMicrocircleList('','','','');
});

//查看
function seeMicroCircle(microcircleId){
    console.log(microcircleId);
    layer.open({
        type: 2,
        title: "管理微圈",
        area: ['1000px','550px'],
        content:"/MicroCircle/seeMicroCircle.html",
        success: function (layero,index) {
            //addLog(3,5,'查看微圈');
            var microCircleData =  JSON.parse(localStorage.getItem("microCircleData"));
            var obj = layero.find('iframe').contents();
            console.log(microCircleData);
            obj.find("#headerImage").attr("src",microCircleData.acatarUrl,);
            obj.find("#p_name").text(microCircleData.trueName);
            obj.find("#span_title").text(microCircleData.artcleTitle);
            obj.find("#titleid").text(microCircleData.artcleTitle);
            obj.find("#span_user").text(microCircleData.trueName);
            $.ajax({
                url:'/microcircle/queryMicroCircleClassification',
                type: "post",
                dataType:'json',
                data: {"acticleCategroyId":microCircleData.acticleCategroyId},
                success:function (data) {
                    if (data.data != null){
                        obj.find("#span_fenlei").text(data.data.artcleCategroyName);
                    }
                }
            });
            obj.find("#span_date").text(microCircleData.releaseDate);
            obj.find("#span_id").text(microCircleData.account);
            obj.find("#text_id").text(microCircleData.article);
            console.log(microCircleData.artcleUrl);
            if (microCircleData.artcleUrl != null && microCircleData.artcleUrl != ''){
                obj.find("#artcleUrl").css("display","inline");
                obj.find("#artcleUrl").attr("src",microCircleData.artcleUrl);
            }
            obj.find("input[name=userName]").val(user.trueName);
            obj.find("input[name=userNum]").val(user.account);
        }
    });
}

//删除
delMicroCircle = function delMicroCircle(microcircleId) {
    layer.open({
        type:1,
        title: "提示信息",
        content:"<div style='font-size: 20px ; color: red; margin:30px  ;'>是否删除此轮播图?</div>",
        area:['300px','200px'],
        btn:["确定","取消"],
        yes: function (index,layero) {
            $.ajax({
                url: "/microcircle/delMicroCircle",
                dataType: "json",
                type: "post",
                data: {"microcircleId":microcircleId},
                success: function (data) {
                    addLog(3,3,'删除微圈');
                    getMicrocircleList('','','','');
                    layer.msg("删除成功");
                    layer.close(index);
                    var arr = localStorage.getItem("numArr");
                    var numArr = arr.split(",");
                    window.parent.frames[numArr[numArr.length - 2]].location.reload();
                }
            });
        },
        btn2: function (index,layero) {
            layer.close(index);
        }
    });
}

//添加操作日志
function addLog(logType,type,remark) {
    var user = JSON.parse(localStorage.getItem("user"));
    var userId = user.userId;
    $.ajax({
        url: "/microcircle/addLog",
        dataType: "json",
        type: "post",
        data: {"logType":logType,"type":type,"userId":userId,"remark":remark},
        success: function (data) {

        }
    });
}

//返回
function backOff() {
    var arr = localStorage.getItem("numArr");
    var numArr = arr.split(",");
    numArr.pop();
    window.parent.layui.element.tabChange('tab',numArr[numArr.length - 1]);
    localStorage.setItem("numArr",numArr);
}

//刷新
function refresh() {
    window.location.reload();
}